package com.wennn.top.shop.biz.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wennn.top.common.vo.IResult;
import com.wennn.top.core.util.CoreConst;
import com.wennn.top.oss.OSSFactory;
import com.wennn.top.security.util.ContextUtil;
import com.wennn.top.shop.biz.user.entity.YxUser;
import com.wennn.top.shop.biz.user.es.UserStatus;
import com.wennn.top.shop.biz.user.es.UserType;
import com.wennn.top.shop.biz.user.mapper.YxUserMapper;
import com.wennn.top.shop.biz.user.service.IYxUserService;
import com.wennn.top.sms.mail.service.JMailService;
import com.wennn.top.util.ComUtil;
import com.wennn.top.util.DateUtil;
import com.wennn.top.web.user.dto.YxUserDto;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author wennn
 * @since 2020-04-18
 */
@Service
public class YxUserServiceImpl extends ServiceImpl<YxUserMapper, YxUser> implements IYxUserService {

    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private JMailService jMailService;


    private static String defaultAvatar = "http://www.wennn.top:8802/static/images/nl.jpg";

    @Override
    public IResult register(YxUser unSaftUser) {
        // 1.校验是否名称重复
        QueryWrapper<YxUser> query = Wrappers.query();
        query.lambda().eq(YxUser::getUsername,unSaftUser.getUsername());
        int count = this.count(query);
        if(count > 0){
            return IResult.fail(CoreConst.FAIL,"该账号已经被注册");
        }

        YxUser yxUser = new YxUser();
        yxUser.setUsername(unSaftUser.getUsername());
        yxUser.setAccount(unSaftUser.getUsername());
        yxUser.setNickname(unSaftUser.getUsername());
        yxUser.setRealName(unSaftUser.getUsername());


        yxUser.setPwd(unSaftUser.getPassword());
        yxUser.setPhone(unSaftUser.getPhone());
        yxUser.setEmail(unSaftUser.getEmail());

        yxUser.setAddIp(unSaftUser.getAddIp());
        yxUser.setAvatar(defaultAvatar);

        yxUser.setAddTime(DateUtil.nowIntTime());
        yxUser.setLevel(0);
        yxUser.setNowMoney(BigDecimal.ZERO);
        yxUser.setUserType(UserType.USER.getCode());

        yxUser.setStatus(UserStatus.normal.getCode());

        String enPwd =  bCryptPasswordEncoder.encode(unSaftUser.getPassword());
        yxUser.setPassword(enPwd);
        return save(yxUser)?IResult.ok().msg("注册成功"):IResult.fail(CoreConst.FAIL,"注册失败了");
    }


    /**
     * 忘记密码
     * @param username
     * @return
     */
    @Override
    public IResult forgetPwd(String username) {
        QueryWrapper<YxUser> query = Wrappers.query();
        query.lambda().eq(YxUser::getUsername,username);
        YxUser user = this.getOne(query);

        if(null == user){
            return IResult.fail(CoreConst.FAIL,"该账号不存在");
        }else if(!user.getStatus()){
            return IResult.fail(CoreConst.FAIL,"该账号已经禁用");
        }

        String newPwd = ComUtil.randomPwd();
        while (bCryptPasswordEncoder.matches(user.getPassword(),newPwd)){
            newPwd = ComUtil.randomPwd();
        }

        user.setPassword(bCryptPasswordEncoder.encode(newPwd));
        jMailService.sendMail(user.getEmail(),"密码重新为> "+newPwd);
        return IResult.ok();
    }


    /**
     *
     * @param inYxUser
     * @param avatarFile
     * @return
     */
    @Override
    public IResult modifyLoginUser(YxUserDto inYxUser, MultipartFile avatarFile) {
        Integer id = ContextUtil.getUser().getId();
        YxUser yxUser = this.getById(id);
        if (Objects.isNull(yxUser)) {
            return IResult.fail(CoreConst.NO_FOUND, "修改失败，请重新登陆");
        }

        try {
            String upload = OSSFactory.build().upload(avatarFile);
            yxUser.setAvatar(upload);
        } catch (Exception e) {
            e.printStackTrace();
        }

        yxUser.setNickname(inYxUser.getNickname());
        // 性别
        yxUser.setEmail(inYxUser.getEmail());
        yxUser.setBirthday(inYxUser.getBirthday());
        boolean b = this.updateById(yxUser);
        return b ? IResult.ok().msg("修改成功") : IResult.fail("保存失败");
    }
}
